package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.BizLog;
import com.geek.factory.result.Result;
import com.geek.factory.service.IBizLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务操作日志管理控制器
 */
@RestController
@RequestMapping("/biz-log")
@Api(tags = "后台系统的 - 业务操作日志模块")
@Slf4j
@CrossOrigin
public class BizLogController {

    @Autowired
    private IBizLogService bizLogService;

    @ApiOperation("通过ID查询业务操作日志信息")
    @GetMapping("/{logId}")
    public Result findBizLogById(@ApiParam("日志ID") @PathVariable("logId") Long logId) {
        BizLog bizLog = bizLogService.getById(logId);
        log.info("bizLog: {}", bizLog);
        if (bizLog != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", bizLog);
        }
        return new Result(SuccessConstant.FAIL, "业务操作日志记录不存在");
    }

    @ApiOperation("根据ID删除业务操作日志")
    @DeleteMapping("/{logId}")
    public Result deleteBizLog(@ApiParam("日志ID") @PathVariable("logId") Long logId) {
        boolean isSuccess = bizLogService.removeById(logId);
        log.info("删除业务操作日志ID: {}, 结果: {}", logId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("批量删除业务操作日志")
    @DeleteMapping("/batch")
    public Result batchDeleteBizLog(@RequestBody Map<String, List<Long>> request) {
        List<Long> logIds = request.get("logIds");
        if (logIds == null || logIds.isEmpty()) {
            return new Result(SuccessConstant.FAIL, "请选择要删除的日志记录");
        }

        boolean isSuccess = bizLogService.removeByIds(logIds);
        log.info("批量删除业务操作日志IDs: {}, 结果: {}", logIds, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "批量删除成功");
        }
        return new Result(SuccessConstant.FAIL, "批量删除失败");
    }

    @ApiOperation("分页查询业务操作日志列表")
    @GetMapping("/page")
    public Result getBizLogPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String operator,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String method,
            @RequestParam(required = false) Boolean success,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime
    ) {
        QueryWrapper<BizLog> wrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(operator)) {
            wrapper.like("operator", operator);
        }
        if (StringUtils.isNotBlank(action)) {
            wrapper.like("action", action);
        }
        if (StringUtils.isNotBlank(method)) {
            wrapper.like("method", method);
        }
        if (success != null) {
            wrapper.eq("success", success);
        }
        if (startTime != null) {
            wrapper.ge("create_time", startTime);
        }
        if (endTime != null) {
            wrapper.le("create_time", endTime);
        }
        wrapper.orderByDesc("create_time");

        Page<BizLog> page = new Page<>(pageNum, pageSize);
        Page<BizLog> resultPage = bizLogService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("records", resultPage.getRecords());
        data.put("total", resultPage.getTotal());
        data.put("current", resultPage.getCurrent());
        data.put("size", resultPage.getSize());
        data.put("pages", resultPage.getPages());

        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有业务操作日志列表")
    @GetMapping("/list")
    public Result getAllBizLogs() {
        List<BizLog> bizLogs = bizLogService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", bizLogs);
    }

    @ApiOperation("获取业务操作日志统计信息")
    @GetMapping("/stats")
    public Result getBizLogStats(
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime
    ) {
        Map<String, Object> stats = new HashMap<>();

        QueryWrapper<BizLog> wrapper = new QueryWrapper<>();
        if (startTime != null) {
            wrapper.ge("create_time", startTime);
        }
        if (endTime != null) {
            wrapper.le("create_time", endTime);
        }

        // 统计总数
        long totalLogs = bizLogService.count(wrapper);

        // 统计成功的数量
        QueryWrapper<BizLog> successWrapper = new QueryWrapper<>();
        if (startTime != null) {
            successWrapper.ge("create_time", startTime);
        }
        if (endTime != null) {
            successWrapper.le("create_time", endTime);
        }
        successWrapper.eq("success", true);
        long successLogs = bizLogService.count(successWrapper);

        // 统计失败的数量
        QueryWrapper<BizLog> failWrapper = new QueryWrapper<>();
        if (startTime != null) {
            failWrapper.ge("create_time", startTime);
        }
        if (endTime != null) {
            failWrapper.le("create_time", endTime);
        }
        failWrapper.eq("success", false);
        long failLogs = bizLogService.count(failWrapper);

        // 统计平均执行时间
        Double avgTimeCost = bizLogService.selectAvgTimeCost(wrapper);

        stats.put("totalLogs", totalLogs);
        stats.put("successLogs", successLogs);
        stats.put("failLogs", failLogs);
        stats.put("successRate", totalLogs > 0 ? (double) successLogs / totalLogs * 100 : 0);
        stats.put("avgTimeCost", avgTimeCost != null ? avgTimeCost : 0);

        return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
    }

    @ApiOperation("根据操作人查询日志列表")
    @GetMapping("/operator/{operator}")
    public Result getLogsByOperator(@ApiParam("操作人") @PathVariable("operator") String operator) {
        QueryWrapper<BizLog> wrapper = new QueryWrapper<>();
        wrapper.eq("operator", operator);
        wrapper.orderByDesc("create_time");

        List<BizLog> logs = bizLogService.list(wrapper);
        return new Result(SuccessConstant.SUCCESS, "查询成功", logs);
    }

    @ApiOperation("根据操作类型查询日志列表")
    @GetMapping("/action/{action}")
    public Result getLogsByAction(@ApiParam("操作类型") @PathVariable("action") String action) {
        QueryWrapper<BizLog> wrapper = new QueryWrapper<>();
        wrapper.eq("action", action);
        wrapper.orderByDesc("create_time");

        List<BizLog> logs = bizLogService.list(wrapper);
        return new Result(SuccessConstant.SUCCESS, "查询成功", logs);
    }

    @ApiOperation("清空所有日志")
    @DeleteMapping("/clear")
    public Result clearAllLogs() {
        // 这里可以添加权限检查，只有管理员才能清空日志
        boolean isSuccess = bizLogService.remove(null);
        log.info("清空所有业务操作日志, 结果: {}", isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "清空成功");
        }
        return new Result(SuccessConstant.FAIL, "清空失败");
    }
}